    import org.apache.commons.net.telnet.TelnetClient;

import java.io.IOException;
    import java.io.InputStream;
import java.io.PrintStream;

    public class Telnet {
    private TelnetClient telnet = new TelnetClient();
    private InputStream in;
    private PrintStream out;
    public String[] comandos = new String[200];
    String tmp_cmd = new String();
    public Telnet(String path) {
    try {
    // Connect to the specified server
    telnet.connect("localhost", 4212);
    // Get input and output stream references
    }
    catch (Exception e) {
    	try {
    		System.out.println("abrindo");
			Runtime rt = Runtime.getRuntime();
			//String[]callAndArgs= {"\"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\" -vvv -I rc "+"\""+ b +"\""+" --sout \"#transcode{vcodec=h264,vb=800,scale=1,acodec=mp4a,ab=128,channels=2,samplerate=44100}:std{access=http,mux=ts,dst=:8080/teste}\""};
			String callAndArgs= "\""+ path + "\" -I telnet --telnet-password 456";
			//String callAndArgs= "\"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc\" -I telnet";
			Process p=rt.exec(callAndArgs);
            p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close();
            //System.out.println(Arrays.toString(callAndArgs));
            System.out.println("abriu");
            
            telnet.connect("localhost", 4212);
           
            }
		
            catch (IOException b) {
                System.out.println("erro abrindo o VLC");
                return;
            }	
    }
    in = telnet.getInputStream();
    out = new PrintStream(telnet.getOutputStream());
    readUntil("Password: ");
    write("456");
    this.readUntil(">");
    }

    public String readUntil(String pattern) {
    try {
    char lastChar = pattern.charAt(pattern.length() - 1);
    StringBuffer sb = new StringBuffer();
    char ch = (char) in.read();
    while (true) {
    System.out.print(ch);
    sb.append(ch);
    if (ch == lastChar) {
    if (sb.toString().endsWith(pattern)) {
    return sb.toString();
    }
    }
    ch = (char) in.read();
    }
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    }
    
    public String saveUntil(String pattern) {
        try {
        char lastChar = pattern.charAt(pattern.length() - 1);
        StringBuffer sb = new StringBuffer();
        StringBuffer cmd = new StringBuffer();
        char ch = (char) in.read();
        int i=0;
        while (true) {
        //System.out.print(ch);
        sb.append(ch);
        cmd.append(ch);
        if (ch == 10 ) {
        	comandos[i] = cmd.toString();
        	i++;
        	cmd.delete(0,cmd.length());
        }
        if (ch == lastChar) {
        	System.out.println(sb.toString());
        	if (sb.toString().endsWith(pattern)) {
        		//return sb.toString();
				return sb.toString().substring(0, sb.toString().length()-pattern.length());
        	}
        }
        ch = (char) in.read();
        }
        }
        catch (Exception e) {
        e.printStackTrace();
        }
        return null;
        }

    public void write(String value) {
    try {
    out.println(value);
    out.flush();
    System.out.println(value);
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }


    public void disconnect() {
    try {
    	this.write("shutdown");
    	telnet.disconnect();
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
	public String getLength( String canal ) {
		int i=0;
		long t0 = System.currentTimeMillis();
		long t = t0;
		long timeout = 800;
    	StringBuffer sb = new StringBuffer();
    	String state = "stopped";
    	while ( state.contains("stopped") && ((t-t0) < timeout) ) {
    		t = System.currentTimeMillis();
    		sb.delete(0, sb.length());
    		System.out.println("Showing...");
			this.write("show " + canal);
	    	this.saveUntil(">");
	    	for(i=0;comandos[i]!=null&&!comandos[i].contains("length : ");i++){
	    		if (comandos[i].contains("state : ")) {
	    			state = comandos[i].split(": ")[1];
	    		}
	    	}
	    	tmp_cmd = comandos[i].split(": ")[1];
	    	for(i=0;i < tmp_cmd.length();i++){
	    		if ( Character.isDigit( tmp_cmd.charAt(i) ) ) {
	    			sb.append( tmp_cmd.charAt(i) );
	    		}
	    	}
    	}
    	if (t-t0 >= timeout)
    		return "timeout";
    	return(sb.toString());
	}
	
	public String getTime( String canal ) {
		//XXX: Comando que pede comprimento
		StringBuffer sb = new StringBuffer();
		int i;
		this.write("show " + canal);
    	this.saveUntil(">");
    	for(i=0;comandos[i]!=null&&!comandos[i].contains("time : ");i++){}
    	tmp_cmd = comandos[i].split(": ")[1];
    	for(i=0;i < tmp_cmd.length();i++){
    		if ( Character.isDigit( tmp_cmd.charAt(i) ) ) {
    			sb.append( tmp_cmd.charAt(i) );
    		}
    	}
    	return(sb.toString());
	}
	
    public void conectarFilme(String canal){
    	String nome = new String();
    	if (canal.equals("")) nome = "null";
	    else nome = canal;
		    this.write("del " + nome);
		    this.readUntil(">");
		    this.write("new " + nome + " broadcast enabled");
		    this.readUntil(">");
		    if (nome.equals("wii")){ //provisorio
		    	this.write("setup " + nome + " output #transcode{vcodec=DIV3,vb=800,scale=1,acodec=mp3,ab=128,channels=2,samplerate=44100}:http{mux=asf,dst=:8080/" + canal + "}");
		    }
		    else
		    	this.write("setup " + nome + " output #transcode{vcodec=h264,vb=800,scale=1,acodec=mp4a,ab=128,channels=2,samplerate=44100}:http{mux=ts,dst=:8080/" + canal + "}");
		    this.readUntil(">");
		    this.write("setup " + nome + "loop");
		    this.readUntil(">");
    }
    public void conectarMusica(String canal){
    	String nome = new String();
    	if (canal.equals("")) nome = "null";
	    else nome = canal;
		    this.write("del " + nome);
		    this.readUntil(">");
		    this.write("new " + nome + " broadcast enabled");
		    this.readUntil(">");
		    this.write("setup " + nome + " output #transcode{vcodec=none,acodec=mp3,ab=128,channels=2,samplerate=44100}:http{mux=raw,dst=:8080/" + canal + "}"); 
		    this.readUntil(">");
		    this.write("setup " + nome + "loop");
		    this.readUntil(">");
    }
    
    public void abrir(String filme,String canal) {
    	String nome = new String();
    	if (canal.equals("")) nome = "null";
	    else nome = canal;
	    try {
		    this.write("setup " + nome + " input \"" + filme + "\"");
		    this.readUntil(">");
		    this.write("control " + nome + " play");
		    this.readUntil(">");     
	    }
	    catch (Exception e) {
	    	e.printStackTrace();
	    }
	    return;
    }
    
    public void playlist(String canal,int soma){
    	int index;
    	this.write("show " + canal);
    	this.saveUntil(">");
    	int i=0;
    	for(i=0;comandos[i]!=null&&!comandos[i].contains("playlistindex : ");i++){}
    	index = Integer.parseInt((String) comandos[i].split(":")[1].subSequence(1,comandos[i].split(":")[1].length()-2)); //os ultimos 2 espaços estão em branco
    	index = index + soma;
    	this.write("control " + canal + " play " + index + "");
    	this.readUntil(">");
    }
    
    
    public void show(){
    	Client.enviar("?nomes", MainPc.type); //para avisar o android que essa lista vai comecar
    	this.write("show");
    	this.saveUntil(">");
    	int i=0;
    	while(comandos[i]!=null&&!comandos[i].contains("media : ( ")){i++;}
    	i++;
    	if (comandos[i]!=null) Client.enviar(comandos[i].subSequence(8,comandos[i].length()-2).toString(), MainPc.type); //o nome comeca com 8 espacos em branco e termina com 2 espacos brancos
    	i++;
    	while(comandos[i]!=null){
	    	while(comandos[i]!=null && comandos[i].contains("            ")){i++;}
	    	if (comandos[i]!=null && !comandos[i].contains("    schedule")){
	    		Client.enviar(comandos[i].subSequence(8,comandos[i].length()-2).toString(), MainPc.type);
	    		i++;
	    	}
	    	System.out.println(comandos[i]);
	    	i++;
    	}
    	Client.enviar("?fim", MainPc.type);
    	return;
    }

    public void comando(String cmd){
    	this.write(cmd);
    	this.readUntil(">");
    }
    } 